// game.ts
import { Player } from './player';
import { GameBoard } from './gameBoard';
import { DeckManager } from './deckManager';
import { FlipCard } from './interfaces';
import { Fruit, FunctionCardType, SpecialCardType } from './enums';

export class Game {
  players: Player[];
  board: GameBoard;
  deckManager: DeckManager;
  currentPlayerIndex: number = 0;
  gameOver: boolean = false;
  winner: Player | null = null;

  constructor(players: Player[]) {
    this.players = players;
    this.board = new GameBoard();
    this.deckManager = new DeckManager();
    this.board.setupInitialCards(this.deckManager);
    if (this.players.length > 0) {
      this.players[0].isActive = true;
    }
  }

  getCurrentPlayer(): Player {
    return this.players[this.currentPlayerIndex];
  }

  flipCard(position: number): { success: boolean; cardType?: number; message?: string } {
    const player = this.getCurrentPlayer();
    const card = this.board.flipCard(position);

    if (!card) {
      return { success: false, message: "位置没有卡牌" };
    }

    // 处理不同类型的牌
    if (card.type >= Fruit.Banana && card.type <= Fruit.Watermelon) {
      return this.handleFruitCard(player, card);
    } else if (card.type >= FunctionCardType.SquirrelGuidance && card.type <= FunctionCardType.OwlPeek) {
      return this.handleFunctionCard(player, card);
    } else if (card.type === SpecialCardType.TigerRush) {
      return this.handleSpecialCard(player, card);
    }

    return { success: false, message: "未知卡牌类型" };
  }

  private handleFruitCard(player: Player, card: FlipCard): { success: boolean; cardType: number; message?: string } {
    const fruit = card.type as Fruit;
    const targetFruits = player.getCurrentTargetFruits();

    if (targetFruits.includes(fruit)) {
      player.collectedFruits.add(fruit);
      this.deckManager.addToDiscard(card);

      if (player.isCurrentAnimalComplete()) {
        player.completeCurrentAnimal(this.deckManager.discardPile);
        
        if (player.currentAnimalIndex >= player.animalCards.length) {
          this.endGame(player);
          return { success: true, cardType: fruit, message: `玩家 ${player.id} 完成所有动物卡，获胜！` };
        }
        return { success: true, cardType: fruit, message: `收集到水果，完成当前动物卡` };
      }
      return { success: true, cardType: fruit, message: "收集到所需水果" };
    } else {
      this.deckManager.addToDiscard(card);
      this.endTurn();
      return { success: false, cardType: fruit, message: "翻到不需要的水果，回合结束" };
    }
  }

  private handleFunctionCard(player: Player, card: FlipCard): { success: boolean; cardType: number; message: string } {
    // 简化处理，实际应根据具体功能实现
    this.deckManager.addToDiscard(card);
    this.endTurn();
    return { 
      success: false, 
      cardType: card.type, 
      message: `翻到功能牌 ${FunctionCardType[card.type]}，无法发动，回合结束` 
    };
  }

  private handleSpecialCard(player: Player, card: FlipCard): { success: boolean; cardType: number; message: string } {
    // 所有本回合收集的水果进弃牌堆，强制结束回合
    player.collectedFruits.forEach(fruit => {
      this.deckManager.addToDiscard({ id: this.deckManager.discardPile.length + 1, type: fruit });
    });
    player.collectedFruits.clear();
    this.deckManager.addToDiscard(card);
    this.endTurn();
    return { 
      success: false, 
      cardType: card.type, 
      message: "翻到萌虎出没，本回合收集的水果作废，回合结束" 
    };
  }

  takeAllNeededFruits(): { success: boolean; message?: string } {
    const player = this.getCurrentPlayer();
    const targetFruits = player.getCurrentTargetFruits();
    const positionsToTake: number[] = [];

    // 查找场面上所有需要的水果
    for (let i = 0; i < 9; i++) {
      const card = this.board.cards[i];
      if (card && targetFruits.includes(card.type as Fruit)) {
        positionsToTake.push(i);
      }
    }

    // 只有当场面上有所需的全部水果时才能拿取
    if (positionsToTake.length === targetFruits.length) {
      positionsToTake.forEach(pos => {
        const card = this.board.flipCard(pos);
        if (card) {
          player.collectedFruits.add(card.type as Fruit);
          this.deckManager.addToDiscard(card);
        }
      });

      if (player.isCurrentAnimalComplete()) {
        player.completeCurrentAnimal(this.deckManager.discardPile);
        
        if (player.currentAnimalIndex >= player.animalCards.length) {
          this.endGame(player);
          return { success: true, message: `玩家 ${player.id} 获胜！` };
        }
      }

      this.endTurn();
      return { success: true, message: "成功拿取所有需要的水果" };
    }

    return { success: false, message: "场面上没有足够的所需水果" };
  }

  endTurn(): void {
    this.board.refillBoard(this.deckManager);
    this.players[this.currentPlayerIndex].isActive = false;
    this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.players.length;
    this.players[this.currentPlayerIndex].isActive = true;
  }

  private endGame(winner: Player): void {
    this.gameOver = true;
    this.winner = winner;
  }

  isGameOver(): boolean {
    return this.gameOver;
  }

  getWinner(): Player | null {
    return this.winner;
  }

  // 获取游戏状态用于显示
  getGameState() {
    return {
      currentPlayer: this.getCurrentPlayer().id,
      board: this.board.cards.map(card => card ? card.type : null),
      players: this.players.map(p => ({
        id: p.id,
        currentAnimal: p.animalCards[p.currentAnimalIndex]?.name || '已完成',
        collectedFruits: Array.from(p.collectedFruits),
        animalsCompleted: p.currentAnimalIndex
      })),
      deckSize: this.deckManager.getDeckSize(),
      discardPileSize: this.deckManager.getDiscardPileSize()
    };
  }
}